package com.huixi.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huixi.Enums.JsonStatus;
import com.huixi.config.properties.JwtProperties;
import com.huixi.entity.User;
import com.huixi.service.LoginService;
import com.huixi.service.UserService;
import com.huixi.utils.CookieUtils;
import com.huixi.utils.ExecutionContext;
import com.huixi.utils.JsonResult;

@Controller
public class IndexController {

	/*@Resource
	private AuthService authService;*/

	@Resource
	private UserService userService;

	@Autowired
	private JwtProperties jwtProperties;

	@Autowired
	private LoginService loginService;

	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, HttpSession session) {
		JsonResult jsonResult = loginService.getUserBySession(session);
		request.setAttribute("userInfo", (User) jsonResult.getData());
		return "index";
	}

	@RequestMapping(value = "/login")
	public String login(Model model, String redirect) {
		model.addAttribute("redirect", redirect);
		return "login";
	}

	@RequestMapping(value = "/register")
	public String register() {
		return "register";
	}

	@RequestMapping(value = "/doLogin")
	@ResponseBody
	public JsonResult doLogin(User user, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		User userInfo = userService.queryUser(user.getUsername(), user.getPassword());
		if (userInfo == null) {
			return JsonResult.build(JsonStatus.ERROR.getCode(), "用户名或密码错误");
		}
		userInfo.setPassword(null);
		session.setAttribute("userInfo", userInfo);
		session.setMaxInactiveInterval(3 * 60);
		// 将当前登录用户存储在线程变量里，方便获取
		// ExecutionContext.set(ExecutionContext.USER_ID,
		// String.valueOf(userInfo.getId()));

		return JsonResult.ok();
	}

	@RequestMapping(value = "/doRegister")
	@ResponseBody
	public JsonResult doRegister(User user) {
		try {
			userService.registerUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			JsonResult.build(JsonStatus.ERROR.getCode(), "注册失败");
		}
		return JsonResult.ok();
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "/logout")
	@ResponseBody
	public JsonResult logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		session.removeAttribute("userInfo");
		//CookieUtils.deleteCookie(request, response, jwtProperties.getCookieName());
		//ExecutionContext.setContextMap(null);
		return JsonResult.ok();
	}
}
